<?php
/**
 * 
 * @author tangbl
 *
 */
class ReplyAction extends CommonAction {
	
	public function _initialize() {
		parent::_initialize();
		parent::_initmenu();	
	}
	
	/**
	 * 回复列表
	 */
    public function index(){
		if(IS_AJAX){
			
			import('ORG.Util.Page');
			$model     = M("Reply");
			
			$orderDesc = $this->_get("orderDirection","trim","desc");;
			$orderName = $this->_get("orderName","trim","addtime");
			$pageNum   = $this->_get("pageNum","intval",C('web_admin_pagenum'));
			$nowPage   = $this->_get("p","intval",1);
			
			$map       = unescape($this->_get("where"));
			$map       = "1=1 ".$map;
			$count     = $model->where($map)->count();
			$Page      = new Page($count);
			$list      = $model->where($map)->order($orderName.' '.$orderDesc)
						->page($nowPage.','.$pageNum)->select();
			
			$totalPage = ceil($count/$pageNum);
			$jsonData  = array('page'=>$nowPage,'total'=>$count,'rows'=>array(),'totalPage'=>$totalPage);
			$replys    = C('REPLY_TYPE');
			$events    = C('EVENT_TYPE');
			$retypes   = C('WECHAT_REPLY_TYPE');
			$upd       = L('cfg_list_itf_btn_modify');
			$del       = L('cfg_list_itf_btn_delete');
			foreach($list AS $row){
				$value    = '' ;
				$location = '';
				if($row['reply_type'] == 1){
					$value = L('cfg_form_wechat_keywords').":".$row['keywords'];
				}elseif($row['reply_type'] == 2){
					$value  =  "".$row['keywords']."";
					/*$value .=  'lx:'.$row['location_lx'].',ly:'.$row['location_ly'].'<br/>'.
					 'rx:'.$row['location_rx'].',ry:'.$row['location_ry'];*/
					if($row['islocation']==1){
						$location = '<a class="btn"><i class="icon-map-marker"></i></a> ';
						$value   .= '('.L('rpl_form_ele_islocation').')';
					}else{
						$location = '<a class="btn blue islocation"  data-id="'.$row['id'].'" title="'.L('rpl_form_ele_set_location').'"><i class=" icon-map-marker"></i></a> ';
					}
			
				}elseif($row['reply_type'] == 3){
					if($row['event_type'] == 3){
						$value = L('cfg_form_wechat_reply_mneu')."[".L('mwt_form_placeholder_cmd')."]:".$row['event_value'];
					}else{
						$etype = $events[$row['event_type']];
						$value = L($etype);
					}
				}
				$entry = array('id'=>$row['id'],
				'cell'=>array(
					'id'         => $row['id'],
					'retype'     => L($retypes[$row['retype']]),
					'reply_type' => get_array_key($replys,$row['reply_type'],true),
					'content'    => $value,
					'addtime'    => date('Y-m-d',$row['addtime']),
					'deal'       => $location.
					'<a href="#" class="btn green cacheone"  data-id="'.$row['reply_solevar'].'"><i class="icon-cloud"></i></a>
				 	 <a href="'.__URL__.'/edit/id/'.$row['id'].'" class="btn blue"  title="'.$upd.'"><i class="icon-edit"></i></a>
				     <a href="#" class="btn red delAlone"  data-id="'.$row['id'].'" title="'.$del.'"><i class="icon-remove"></i></a>'
				),
				);
				$jsonData['rows'][] = $entry;
			}
			$this->ajaxReturn($jsonData,'JSON');
			
		}else{
			$this->display();
		}
    }

	/**
	 * 添加回复
	 */
	public function add(){
		$reply     = D('Reply');
		$replyCont = D('ReplyContent');

		if(IS_POST){
			$flag  = true ;
			$reply_solevar = $this->_param("reply_solevar");
			$type          = $this->_param("type","intval",0);
			$retype        = $this->_param("retype");
			
			$data['retype']          = $retype ;
			$data['reply_type']      = $type ;
			$data['reply_solevar']   = $reply_solevar;
			$data['addtime']         = time() ;
			
			if($type == 1){//关键字自动回复
				$keywords   = $this->_post("wechat_keywords");
				$exsitsKeys = $reply->getReplyByKey(array($keywords));
				if(!array_key_exists($keywords,$exsitsKeys)){
					$data['keywords'] = $keywords;
					$id = $reply->add($data);
				}
			}elseif($type == 2){//地理位置自动回复
				$data['islocation'] = $this->_post("islocation","intval",2);
				$data['keywords']   = $this->_post("keywords");
				$location = $this->_post("location");
				$arrays   = explode(',',$location);
				$data['location_lx'] = $arrays[0];
				$data['location_ly'] = $arrays[1];
				$data['location_rx'] = $arrays[2];
				$data['location_ry'] = $arrays[3];
				$id = $reply->add($data);
			}elseif($type == 3){//事件类型自动回复
				$event = $this->_post("event_type");
				$data['event_type'] = $event;
				if($event == 3){
					$menu_type = $this->_post("menu_type");
					$data['event_value'] = $menu_type;	
				}
				$id = $reply->add($data);//没有判断该内容是否已经添加该事件类型回复 todo
			}else{//其他事件类型回复
				$flag = false;	
				if($type){
					if(!$reply->getReplyByType($type)){//判断该事件类型是否存在reply
						$id   = $reply->add($data);
						$flag = true;	
					}else{
						$res  = L('rpl_form_valid_event_exsists');	
					}
				}
			}
			if($flag){
				wlog(1);
				
				$lists = $replyCont->contentByReplySolevar($reply_solevar);	
				foreach($lists as $v){
					$data['id'] = $v['id'];
					$replyCont->save($data);
				}
				/*$funcs = "cache_reply_".$retype;
				$replyCont->$funcs($reply_solevar);*/
			}
			$this->assign("jumpUrl",U('/Reply/index'));
			$this->success(L('cfg_form_tipmsg_addsucc'));
		}else{
			$solevar = $this->_param("solevar");
			//根据内容的solevar 判断该内容的其他事件类型是否已经存在
			$rows    = $reply->validByReplyType();
			$html   = '';
			$replys = C('REPLY_TYPE');
			foreach($replys as $k=>$v){
				if(!in_array($k,$rows)){
					$html .= "<option value=".$k.">".L($v)."</option>";
				}else{
					$html .= "<option value=".$k." disabled='disabled'>".L($v)."</option>";
				}
			}
			$this->assign("retype",create_option_key(C('WECHAT_REPLY_TYPE'),-1,true));
			$this->assign("type",$html);
			$this->display();
		}
    }
	
	/**
	 * 编辑回复
	 */
	public function edit(){
		
		$reply     = D('Reply');
		if(IS_POST){
			$id            = $this->_param("id","intval",0);
			$reply_solevar = $this->_param("reply_solevar");
			$type          = $this->_post("type","intval",0);
			$retype        = $this->_param("retype");
			
			$data['retype']          = $retype ;
			$data['id']              = $id ;
			$data['reply_type']      = $type ;
			$data['reply_solevar']   = $reply_solevar;
			
			$rows  = $reply->find($id);
			$data  = $reply->emptyReply($data);//初始化表单值
			$flag  = true ;
			$res   = L('cfg_form_tipmsg_editsucc');
			if($type == 1){//关键字自动回复
				$flag = false;
				$keywords   = $this->_post("wechat_keywords");
				$exsitsKeys = $reply->getReplyByKey(array($keywords));
				if(!array_key_exists($keywords,$exsitsKeys)){
					$data['keywords'] = $keywords;
					$reply->save($data);
					$flag = true;
				}else{
					if($keywords!=$rows['keywords']){
						$res  = L('rpl_form_valid_key_exsists');
					}
				}
			}elseif($type == 2){//地理位置自动回复
				$data['islocation'] = $this->_post("islocation","intval",2);
				$data['keywords']   = $this->_post("keywords");
				$location = $this->_post("location");
				if($location){
					$arrays   = explode(',',$location);
					$data['location_lx'] = $arrays[0];
					$data['location_ly'] = $arrays[1];
					$data['location_rx'] = $arrays[2];
					$data['location_ry'] = $arrays[3];
				}else{
					$data['location_lx'] = $rows['location_lx'];
					$data['location_ly'] = $rows['location_ly'];
					$data['location_rx'] = $rows['location_rx'];
					$data['location_ry'] = $rows['location_ry'];
				}
				$reply->save($data);
			}elseif($type == 3){//事件类型自动回复
				$event = $this->_post("event_type");
				$data['event_type'] = $event;
				if($event == 3){
					$menu_type = $this->_post("menu_type");
					$data['event_value'] = $menu_type;
					if($menu_type==$rows['event_value'])
						$flag = false;	
				}else{
					if($event==$rows['event_type'])
						$flag = false;
				}
				if($flag)
					$reply->save($data);//没有判断该内容是否已经添加该事件类型回复 todo
			}else{//其他事件类型回复
				$flag = false;
				if($type){
					if($type!=$rows['reply_type']){
						if(!$reply->getReplyByType($type)){//判断该事件类型是否存在reply
							$reply->save($data);
							$flag = true;
						}else{
							$res  = L('rpl_form_valid_event_exsists');	
						}
					}
				}
			}
			
			if($flag){
				wlog(1,"",$id);
				
				$replyCont = D('ReplyContent');
				$lists     = $replyCont->contentByReplySolevar($reply_solevar);	
				foreach($lists as $v){
					$data['id'] = $v['id'];
					$replyCont->save($data);
				}
				/*$funcs = "cache_reply_".$retype;
				$replyCont->$funcs($reply_solevar);*/
			}else{
				$rec['id']     = $id;
				$rec['retype'] = $retype;
				$reply->save($rec);
			}
			$this->assign("jumpUrl",U('/Reply/index'));
			$this->success($res);
		}else{
			$id      = $this->_param("id","intval",0);
			$rec     = $reply->find($id);
			//根据内容的solevar 判断该内容的其他事件类型是否已经存在
			$rows    = $reply->validByReplyType();
			$html   = '';
			$replys = C('REPLY_TYPE');
			foreach($replys as $k=>$v){
				if(!in_array($k,$rows)||($k==$rec['reply_type'])){
					$html .= "<option value=".$k." >".L($v)."</option>";
				}else{
					$html .= "<option value=".$k." disabled='disabled'>".L($v)."</option>";
				}
			}
			$this->assign("retype",create_option_key(C('WECHAT_REPLY_TYPE'),$rec['retype'],true));
			$this->assign("type",$html);
			$this->assign("reply",$rec);
			$this->display();	
		}
	}
	
	/**
	 * 内容关联回复列表
	 */
	public function content_reply(){
		$solevar = $this->_param("solevar");
		$view    = D("ReplyView");
		$lists   = $view->where("content_solevar='".$solevar."'")->select();
		//echo $view->getLastSql();
		
		$rows    = array();
		$replys  = C('REPLY_TYPE');
		$events  = C('EVENT_TYPE');
		$retypes = C('WECHAT_REPLY_TYPE');
		foreach($lists as $k=>$v){
			$rows[$k]['reply_type']    = get_array_key($replys,$v['reply_type'],true);
			$value = '' ;
			if($v['reply_type'] == 1){
				$value = L('cfg_form_wechat_keywords').":".$v['keywords'];
			}elseif($v['reply_type'] == 2){
				$value =  $v['keywords'];
			}elseif($v['reply_type'] == 3){
				if($v['event_type'] == 3){
					$value = L('cfg_form_wechat_reply_mneu')."[".L('mwt_form_placeholder_cmd')."]:".$v['event_value'];	
				}else{
					$etype = $events[$v['event_type']];
					$value = L($etype);
				}
			}
			$rows[$k]['retype']        = L($retypes[$v['retype']]);
			$rows[$k]['reply_content'] = $value ;
			$rows[$k]['deal']          = '<a href="#" class="btn red delAlone"  data-id="'.$v['contentid'].'">
										  <i class="icon-remove"></i></a>';	
		}
		$jsonData  = array('rows'=>$rows);
		$this->ajaxReturn($jsonData,'JSON');
	}
	
	/**
	 * 内容关联添加回复
	 */
	public function content_add(){
		$reply     = D('Reply');
		$replyCont = D('ReplyContent');
		
		$content_solevar = $this->_param("content_solevar");
		$reply_solevar   = $this->_param("reply_solevar");
		$table           = $this->_param("table");
		if(IS_POST){
			$type      = $this->_post("type","intval",0);
			$retype    = $this->_param("retype");
			
			$data['retype']          = $retype ;
			$data['reply_type']      = $type ;
			$data['content_solevar'] = $content_solevar;
			$data['reply_solevar']   = $reply_solevar;
			$data['addtime']         = time() ;
			$data["content_table"]   = $table;
			//获取内容的名称
			$data['title']           = $replyCont->contentBySolevar($table,$content_solevar);
			//echo "title:".$data['title'];
			if($type == 1){//关键字自动回复
				$keywords  = $this->_post("wechat_keywords");
				if(is_array($keywords)){
					$exsitsKeys = $reply->getReplyByKey($keywords);
					foreach($keywords as $v){
						$data["keywords"] = $v;	
						if(!array_key_exists($v,$exsitsKeys)){
							$data['reply_solevar'] = create_id();
							$reply->add($data);//生成的多个reply_solevar 
						}else{
							$data['reply_solevar'] = $exsitsKeys[$v];
						}
						$replyCont->add($data);
					}
				}
			}elseif($type == 2){//地理位置自动回复
				$location = $this->_post("location");
				$data['islocation'] = $this->_post("islocation","intval",2);
				$data['keywords']   = $this->_post("keywords");
				$arrays   = explode(',',$location);
				$data['location_lx'] = $arrays[0];
				$data['location_ly'] = $arrays[1];
				$data['location_rx'] = $arrays[2];
				$data['location_ry'] = $arrays[3];
				
				$condata             = $data ;
				$reply->add($data);
				$replyCont->add($condata);
			}elseif($type == 3){//事件类型自动回复
				$event = $this->_post("event_type");
				$data['event_type'] = $event;
				if($event == 3){
					$menu_type = $this->_post("menu_type");
					$data['event_value'] = $menu_type;	
				}
				$reply->add($data);//没有判断该内容是否已经添加该事件类型回复 todo
				$replyCont->add($data);
			}else{//其他事件类型回复
				if($type){
					$replyCont->where('content_solevar="'.$content_solevar.'" and reply_type='.$type)->delete();
					$replyCont->add($data);
					if(!$reply->getReplyByType($type)){//判断该事件类型是否存在reply
						$reply->add($data);
					}
				}
			}
			echo "<script type='text/javascript'>window.parent.$('#btn_refresh').click();
				   window.parent.$('.aui_close').click();</script>";		

		}else{
			$solevar = $this->_param("solevar");
			//根据内容的solevar 判断该内容的其他事件类型是否已经存在
			$rows    = $replyCont->validReplyBySolevar($content_solevar);
			
			$html   = '';
			$replys = C('REPLY_TYPE');
			foreach($replys as $k=>$v){
				if(!in_array($k,$rows)){
					$html .= "<option value=".$k.">".L($v)."</option>";
				}else{
					$html .= "<option value=".$k." disabled='disabled'>".L($v)."</option>";
				}
			}
			$retype = $this->_param("retype","","-1");
			$this->assign("retype",create_option_key(C('WECHAT_REPLY_TYPE'),$retype,true));
			$this->assign("type",$html);
			$this->display();
		}	
    }
	
	/**
	 * 回复内容添加
	 */
	function reply_content_list(){
		if(IS_POST){
			$replyCont    = D('ReplyContent');
			$content_type = $this->_param("content_type");
			$ids          = $this->_param("id");
			$solevar      = $this->_param("solevar");
			
			/* $reply = $replyCont->replyOneSolevar(array("reply_solevar"=>$solevar));
			$data['retype'] 	   = $reply['retype'];
			$data['reply_type']    = $reply['reply_type']; */
			
			$data['reply_solevar'] = $solevar;
			$data['content_table'] = $content_type;
			$data['addtime']       = time();
			
			if($ids){
				$total = C('WECHAT_REPLY_TOTAL');
				
				$lists = $replyCont->contentByReplySolevar($solevar);
				$rows  = array(); 
				foreach($lists as $v){
					$rows[] = $v['content_solevar'];
				}
				$fisint = count($rows);
				
				$lists = $replyCont->contentByIds($content_type,$ids);
				$secint = $total-$fisint;
				
				foreach($lists as $k=>$v){
					if(!in_array($v['solevar'],$rows) && $k<$secint){
						$data['content_solevar'] = $v['solevar'];
						$data['title']           = $v['title'];						
						$replyCont->add($data);
					}
				}
				
				//重新缓存回复对应的内容
				$rows  = $replyCont->replyOneSolevar(array("reply_solevar"=>$solevar));
				if($rows['id']){
					$funcs = "cache_reply_".$rows['retype'];
					$replyCont->$funcs($solevar);
				}
				
			}
			echo "<script type='text/javascript'>window.parent.$('#btn_refresh').click();
					   window.parent.$('.aui_close').click();</script>";
		}else{
			$replyCont    = D('ReplyContent');
			$solevar      = $this->_param("solevar");
			$where        = 'reply_solevar="'.$solevar.'"';
			$lists        = $replyCont->where($where)->order("ordernum desc,addtime desc")->select();
			
			$rows         = array();
			$content_type = C('WECHAT_CONTENT_TYPE');
			foreach($lists as $k=>$v){
				$rows[$k]['id']            = $v['id'];
				$rows[$k]['ordernum']      = $v['ordernum'];
				
				$array = $content_type[$v['content_table']];
				$total = $replyCont->contentTotal($v,$content_type);
				
				$rows[$k]['content_type']  = L($array[0]);
				$rows[$k]['content_title'] = $v['title'].$total;
				$rows[$k]['deal'] = '<a href="#" class="btn red delAlone"  data-id="'.$v['id'].'">
									 <i class="icon-remove"></i></a>';	;
			}
			
			$jsonData  = array('rows'=>$rows);
			$this->ajaxReturn($jsonData,'JSON');
		}
	
	}
	
	/**
	 * 回复关联内容列表
	 */
	public function content_list(){
		
		if(IS_AJAX){
			
			import('ORG.Util.Page');// 导入分页类
				
			$table     = $this->_get("table","trim","Article");
			$user      = M($table);
			
			$orderDesc = $this->_get("orderDirection","trim","desc");
			$orderName = $this->_get("orderName","trim","addtime");
			$pageNum   = $this->_get("pageNum","intval",C('web_admin_pagenum'));
			
			$map       = unescape($this->_get("where"));
			$map       = "1=1 ".$map;
			$count     = $user->where($map)->count();
			
			$Page      = new Page($count);// 实例化分页类 传入总记录数
			$nowPage   = isset($_GET['p'])?$_GET['p']:1;
			$show      = $Page->show();// 分页显示输出
			$list      = $user->where($map)->order($orderName.' '.$orderDesc)
			->page($nowPage.','.$pageNum)->select();
			$totalPage = ceil($count/$pageNum);
			
			$jsonData  = array('page'=>$nowPage,'total'=>$count,'rows'=>array(),'totalPage'=>$totalPage);
			$replys  = C('REPLY_TYPE');
			foreach($list AS $row){
				$entry = array('id[]'=>$row['id'],
						'cell'=>array(
								'id[]'     => $row['id'],
								'lang'     => $row['lang'],
								'title'    => $row['title']
						),
				);
				$jsonData['rows'][] = $entry;
			}
			$this->ajaxReturn($jsonData,'JSON');
			
		}else{
			$content_type_str = '';
			foreach(C('WECHAT_CONTENT_TYPE') as $k=>$v){
				$content_type_str .= '<option value="'.$k.'">'.L($v[0]).'</option>';
			}
			$this->assign("content_type_str",$content_type_str);
			
			$this->display();
			
		}
	}
	
	/**
	 * 删除内容对应的回复记录
	 */
	public function delcont(){
		parent::do_del("ReplyContent");
	}
	
	/**
	 * 删除回复
	 */
	public function del(){
		$id    = $this->_get('id',"intval",0);
		$Reply     = D('Reply');
		$ReplyCont = D('ReplyContent');
		$rows      = $Reply->find($id);
		
		$res1 = $ReplyCont->where("reply_solevar='".$rows['reply_solevar']."'")->delete();
		$res  = $Reply->delete($id);
		if($res) {
			$this->ajaxReturn($res,L("cfg_form_tipmsg_delsucc"),1);
		} else {
			 $this->ajaxReturn(0,L("cfg_form_tipmsg_delfail"),0);
		}
	}
	
	/**
	 * 生成回复缓存
	 */
	public function create_reply_cache(){
		$solevar = $this->_param("solevar");
		$reply   = D("Reply");
		$content = D("ReplyContent");
		if(!$solevar){
			$rows    = $reply->select();
			foreach($rows as $v){
				$funcs   = "cache_reply_".$v['retype'];//news and text 内容回复生成方法
				$content->$funcs($v['reply_solevar']);
			}
			$this->ajaxReturn(1,L("rpl_valid_reply_cache_all"),1);
		}else{
			$rows    = $reply->where("reply_solevar='".$solevar."'")->find();
			$funcs   = "cache_reply_".$rows['retype'];
			$content->$funcs($solevar);
			$this->ajaxReturn(1,L("rpl_form_valid_reply_cache"),1);
		}
	}
	
	/**
	 * 回复内容排序
	 */
	public function sort(){
		$sorts = $this->_POST('sort');
		if(!is_array($sorts))$this->error(L('cfg_form_tipmsg_illgel'));
		
		$content = D("ReplyContent");
		$rid     = $this->_param("id","intval",0);
		$solevar = $this->_param("solevar");
		
		$content->cache_reply_news($solevar);//重新缓存回复内容
		
		foreach ($sorts as $id => $sort) {
			$content->upReplyContent( array('id' =>$id , 'ordernum' =>intval($sort) ) );
		}
		$this->assign("jumpUrl",U('/Reply/edit/id/'.$rid));
		$this->success(L('rpl_oth_sort_succ'));
	}
	
	/**
	 * 回复设置默认位置
	 */
	public function islocation(){
		$id = $this->_param("id","intval",1);
		if(!$id)$this->error(L('cfg_form_tipmsg_illgel'));
		
		$reply   = D("Reply");
		$reply->where('reply_type=2')->save(array('islocation'=>2));
		
		$reply->save(array('islocation'=>1,"id"=>$id));
		
		$this->assign("jumpUrl",U('/Reply/index'));
		$this->success(L('rpl_oth_islocation_succ'));
	}
}